package com.peanut.youfupay.util;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @Description:发送http请求类
 * @author:admin
 * @time:2018年7月17日 下午3:25:32
 */
public class HttpClientHelper {
	/**
	 * @Description:使用HttpClient发送post请求
	 * @author:liuyc
	 * @time:2016年5月17日 下午3:28:23
	 */
	public static String httpClientPost(String urlParam, Map<String, Object> params, String charset) {
		StringBuffer resultBuffer = null;
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(urlParam);
		// 构建请求参数
		List<NameValuePair> list = new ArrayList();
		Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Object> elem = iterator.next();
			list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
		}
		BufferedReader br = null;
		try {
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = client.execute(httpPost);
			// 读取服务器响应数据
			resultBuffer = new StringBuffer();
			br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),charset));
			String temp;
			while ((temp = br.readLine()) != null) {
				resultBuffer.append(temp);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					br = null;
					throw new RuntimeException(e);
				}
			}
		}
		return resultBuffer.toString();
	}

	public static String httpClientFile(String urlParam, Map<String, Object> params, String charset, String fileName) {
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(urlParam);
		// 构建请求参数
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Object> elem = iterator.next();
			list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
		}
//		BufferedReader br = null;
		InputStream br =null;
		FileOutputStream out = null;
		try {
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = client.execute(httpPost);

			int code = response.getStatusLine().getStatusCode();
			System.out.println(code);
			if (code == HttpStatus.SC_OK) {
				File file = new File(fileName);
				out = new FileOutputStream(file);
				br = response.getEntity().getContent();
				byte[] buffer = new byte[4096];
				int readLength = 0;
				while ((readLength = br.read(buffer, 0, 1024)) != -1) {
					out.write(buffer, 0, readLength);
				}
				out.flush();
			} else {
				return "false";
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					br = null;
					throw new RuntimeException(e);
				}
				try {
					if(out != null){
						out.close();
					}
				} catch (IOException e) {
//				logger.error("下载文件失败！");
				}
			}
		}
		return "success";
	}

	/**
	 * @Description:读取一行数据，contentLe内容长度为0时，读取响应头信息，不为0时读正文
	 * @time:2016年5月17日 下午6:11:07
	 */
	private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
		List<Byte> lineByte = new ArrayList<Byte>();
		byte tempByte;
		int cumsum = 0;
		if (contentLength != 0) {
			do {
				tempByte = (byte) is.read();
				lineByte.add(Byte.valueOf(tempByte));
				cumsum++;
			} while (cumsum < contentLength);// cumsum等于contentLength表示已读完
		} else {
			do {
				tempByte = (byte) is.read();
				lineByte.add(Byte.valueOf(tempByte));
			} while (tempByte != 10);// 换行符的ascii码值为10
		}

		byte[] resutlBytes = new byte[lineByte.size()];
		for (int i = 0; i < lineByte.size(); i++) {
			resutlBytes[i] = (lineByte.get(i)).byteValue();
		}
		return new String(resutlBytes, charset);
	}









	/**
	 * 下载文件
	 * @param url
	 * @param destFileName
	 * @return
	 * @throws Exception
	 */
	/*public boolean getFile(String url,String destFileName) throws Exception{


		RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).
				setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST)).
				setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(30000)
				.setConnectTimeout(30000).build();;
		CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm)
				.setDefaultRequestConfig(requestConfig).build();
				InputStream in =null;
		FileOutputStream out = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();

			in = entity.getContent();
			if(in == null){
//				logger.info("文件不存在");
				return false;
			}
			File file = new File(destFileName);
			out = new FileOutputStream(file);
			byte[] buffer = new byte[4096];
			int readLength = 0;
			while((readLength=in.read(buffer)) > 0){
				byte[] bytes = new byte[readLength];
				System.arraycopy(buffer, 0, bytes, 0, readLength);
				out.write(bytes);
			}
			out.flush();
//			logger.info("下载文件成功：{}",destFileName);
			return true;
		} catch (Exception e) {
//			logger.error("下载文件失败！");
			return false;
		}finally {
			try {
				if(in != null){
					in.close();
				}
			} catch (IOException e) {
//				logger.error("下载文件失败！");
			}

			try {
				if(out != null){
					out.close();
				}
			} catch (IOException e) {
//				logger.error("下载文件失败！");
			}
		}
	}*/

}
